<template>
  <el-dialog v-model="drawer" :close-on-click-modal="false" destroy-on-close width="55%" @close="closeMatter" title="采购单">
    <el-form :model="formData" :rules="formRules" ref="formRef" size="small" :inline="false" label-width="100px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="类别" prop="orderType">
            <el-radio-group v-model="formData.orderType">
              <el-radio :label="0">个人采购单</el-radio>
              <el-radio :label="1">企业采购单</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="卖方经办人" prop="contactUserId">
            <el-select v-model="formData.contactUserId" placeholder="请选择经办人" clearable filterable @change="contactChange">
              <el-option v-for="item in contactList" :key="item.id" :value="item.id" :label="item.name"/>
            </el-select>
          </el-form-item>
          <el-form-item label="采购单所属部门" prop="deptId">
            <el-select v-model="formData.deptId" placeholder="请选择所属部门" clearable filterable>
              <el-option v-for="item in deptList" :key="item.id" :value="item.id" :label="item.name"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="供应商" prop="supplierInfoId">
            <el-select v-model="formData.supplierInfoId" placeholder="请选择供应商" @change="supplierChange" filterable clearable>
              <el-option v-for="item in supplierList" :key="item.supplierInfoId" :value="item.supplierInfoId" :label="item.shortName"/>
            </el-select>
          </el-form-item>
          <el-form-item label="联系方式" prop="contactPhone">
            <el-input v-model="formData.contactPhone" placeholder="请填写联系方式" clearable maxlength="16" style="width: 180px"/>
          </el-form-item>
          <el-form-item label="采购单阶段" prop="stage">
            <el-select v-model="formData.stage" placeholder="请选择采购单阶段" clearable filterable>
              <el-option v-for="item in dictMap['OrderStage']" :key="item.value" :label="item.name" :value="item.value"/>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-divider content-position="left">打印区域</el-divider>
      <el-row>
        <el-col :span="12">
          <el-form-item label="采购主题" prop="title">
            <el-input v-model="formData.title" placeholder="请填写采购主题" style="width: 80%" clearable maxlength="32"/>
          </el-form-item>
          <el-form-item label="发货方式" prop="deliveryType">
            <el-select v-model="formData.deliveryType">
              <el-option v-for="item in dictMap['DeliveryType']" :key="item.value" :label="item.name" :value="item.value"/>
            </el-select>
          </el-form-item>
          <el-form-item label="合同金额" prop="amount">
            <el-input-number v-model="formData.amount" :min="0" :max="999999999" :controls="false" :precision="2" style="width: 260px"/>
            <el-checkbox v-model="formData.includeTax" :true-label="0" :false-label="1" style="margin-left: 10px">{{ formData.includeTax == 1 ? '' : '不' }}含税</el-checkbox>
          </el-form-item>
          <el-form-item label="是否开票" prop="invoice">
            <el-radio-group v-model="formData.invoice" @change="invoiceChange">
              <el-radio :label="0">不开票</el-radio>
              <el-radio :label="1">开票</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="采购订单编号" prop="offerNo">
            <el-input v-model="formData.offerNo" placeholder="不填系统自动生成" style="width: 80%" clearable maxlength="64"/>
          </el-form-item>
          <el-form-item label="预计交货日期" prop="occurDate">
            <el-date-picker v-model="formData.occurDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择日期"/>
          </el-form-item>
          <el-form-item label="结款方式" prop="payType">
            <el-select v-model="formData.payType" placeholder="请选择结款方式" clearable filterable>
              <el-option v-for="item in dictMap['PaymentType']" :key="item.value" :value="item.value" :label="item.name"/>
            </el-select>
          </el-form-item>
          <el-form-item label="发票类型" prop="invoiceType">
            <el-radio-group v-model="formData.invoiceType">
              <el-radio :label="0">普通发票</el-radio>
              <el-radio :label="1">增值发票</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="formData.remark" type="textarea" :rows="3"/>
      </el-form-item>
      <el-form-item label="产品清单">
        <el-table :data="formData.productItems" stripe height="240" :header-cell-style="{textAlign: 'center'}" :cell-style="{textAlign: 'center'}">
          <el-table-column label="序号" type="index" width="75"/>
          <el-table-column label="产品名称" width="150" prop="name">
            <template v-slot="{row}">
              <el-select v-model="row.name" allow-create filterable default-first-option clearable>
                <el-option v-for="item in productNames" :key="item.id" :value="item.name" :label="item.name"/>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="型号" width="150" prop="ver">
            <template v-slot="{row}">
              <el-input v-model="row.ver" maxlength="64" clearable/>
            </template>
          </el-table-column>
          <el-table-column label="详情/规格" width="150" prop="specification">
            <template v-slot="{row}">
              <el-input v-model="row.specification" maxlength="255" clearable/>
            </template>
          </el-table-column>
          <el-table-column label="数量" width="100" prop="num">
            <template v-slot="{row}">
              <el-input-number v-model="row.num" :min="0" :max="999999" :controls="false" style="width: 90px" @change="calAmount(row)"/>
            </template>
          </el-table-column>
          <el-table-column label="价格" width="130" prop="price">
            <template v-slot="{row}">
              <el-input-number v-model="row.price" :min="0" :max="999999" :controls="false" :precision="2" style="width: 120px" @change="calAmount(row)"/>
            </template>
          </el-table-column>
          <el-table-column label="小计" width="140" prop="total"/>
          <!--          <el-table-column label="发货方式">-->
          <!--            <template v-slot="{row}">-->
          <!--              <el-select v-model="row.deliveryType">-->
          <!--                <el-option v-for="item in dictMap['DeliveryType']" :key="item.value" :label="item.name" :value="item.value"/>-->
          <!--              </el-select>-->
          <!--            </template>-->
          <!--          </el-table-column>-->
          <el-table-column label="备注" prop="remark">
            <template v-slot="{row}">
              <el-input v-model="row.remark" type="textarea" :rows="2"/>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="90">
            <template v-slot="{$index, row}">
              <el-button type="danger" :icon="Delete" text @click="removeProduct($index, row)">移除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-row style="margin-top: 5px;width: 100%">
          <el-col :span="3" :offset="1">
            <el-button type="primary" :icon="Plus" @click="addProduct" text>添加</el-button>
          </el-col>
          <el-col :span="4">合计：{{ formData.realAmount }} 元</el-col>
          <el-col :span="4">大写：{{ numToChinese(formData.realAmount) }}</el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="合同正文和条款" prop="replenishInstruction">
        <editor v-model="formData.replenishInstruction" height="160px"/>
      </el-form-item>

      <el-divider content-position="left">报价单区域</el-divider>

      <el-form-item label="报价单">
        <el-table :data="formData.quotationList" stripe height="240" :header-cell-style="{textAlign: 'center'}" :cell-style="{textAlign: 'center'}">
          <el-table-column label="名称" prop="title"/>
          <!-- 此处为供应商简称 -->
          <el-table-column label="供应商" prop="shortName"/>
          <el-table-column label="单号" prop="quoteNo"/>
          <el-table-column label="金额" prop="amount"/>
          <el-table-column label="操作">
            <template v-slot="{$index}">
              <el-button type="danger" :icon="Delete" @click="removeQuotation($index)" text>移除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button type="primary" :icon="Plus" @click="openQuoteAdd" style="margin-top: 10px">添加报价单比对</el-button>
      </el-form-item>
    </el-form>

    <!-- 报价单关联 -->
    <el-dialog v-model="quoteVisible" :close-on-click-modal="false" destroy-on-close width="900px" title="关联报价单">
      <el-transfer
          v-model="selectedQuotes"
          filterable
          :titles="['报价单列表', '已选报价单']"
          filter-placeholder="填入关键字搜索"
          :props="{key: 'id', label: 'title'}"
          :data="quoteList"/>
      <template #footer>
        <el-button size="small" @click="quoteVisible = false">关 闭</el-button>
        <el-button size="small" type="primary" @click="confirmQuote">确 定</el-button>
      </template>
    </el-dialog>

    <template #footer>
      <el-row style="text-align: center;padding: 5px 0">
        <el-col :span="6">
          <el-button size="small" @click="closeMatter">关 闭</el-button>
        </el-col>
        <el-col :span="6">
          <el-button size="small" type="primary" @click="saveDraft(formRef)">保存到草稿</el-button>
        </el-col>
        <el-col :span="6">
          <el-button size="small" type="primary" @click="saveOrder(formRef, 0)">保存到采购单列表</el-button>
        </el-col>
        <el-col :span="6">
          <el-button size="small" type="primary" @click="saveOrder(formRef, 1)">保存并提交</el-button>
        </el-col>
      </el-row>
    </template>
  </el-dialog>
</template>

<script>
// 采购单
import {computed, reactive, toRefs, ref} from 'vue'
import {Plus, Delete} from '@element-plus/icons-vue'
import Editor from '/@/components/editor/index.vue'
import {getDictByCodes} from '/@/api/sys/dict'
import {getSupplierSelector} from '/@/api/supplier'
import supplierContact from '/@/api/supplier/supplierContact'
import {getAllowDeptList} from '/@/api/sys/dept'
import purchaseOrderApi from '/@/api/supplier/purchaseOrder'
import {numToChinese} from '/@/utils/common'
import {ElMessage} from 'element-plus'
import {quoteSelector} from '/@/api/supplier/quoteOrder'

export default {
  name: 'PurchaseOrder',
  components: {
    Editor
  },
  emits: ['callback', 'update:code'],
  props: {
    code: {
      type: String,
      default: ''
    },
    supplier: {   // 供应商信息id
      type: String,
      default: null
    },
    editForm: {
      default: null
    }
  },
  setup(props, context) {
    const formRef = ref()
    const {code, supplier, editForm} = toRefs(props)
    let drawer = computed({
      get: () => {
        let flag = code.value == state.formData.type
        if (flag) {
          if (editForm.value) {
            state.formData = JSON.parse(JSON.stringify(editForm.value))
            state.formData.id = editForm.value.id
            state.formData.sourceType = editForm.value.source
            state.formData.offerNo = editForm.value.orderNo
            state.formData.contactUserId = editForm.value.handlerId
            state.formData.contactPhone = editForm.value.handlerPhone
            state.formData.occurDate = editForm.value.predictDeliverDate
            state.formData.amount = editForm.value.contractAmount
            state.formData.realAmount = editForm.value.productAmountSum
            state.formData.payType = editForm.value.paymentType
            state.formData.includeTax = editForm.value.amountTax
            state.formData.orderType = editForm.value.type
            supplierContact.getContactList(state.formData.supplierInfoId).then(res => state.contactList = res.data).catch(e => console.log(e))
          } else {
            resetForm()
          }
          if (supplier.value) {
            state.formData.supplierInfoId = supplier.value
            supplierContact.getContactList(state.formData.supplierInfoId).then(res => state.contactList = res.data).catch(e => console.log(e))
          }
          // // 默认带入自己
          // state.selfId = Cookies.get('userId')
          // state.formData.executorIds = [state.selfId]
          // // 行动时间默认现在
          // let nowTime = formatDate(new Date(), 'YYYY-mm-dd HH:MM:SS')
          // state.formData.actionStartTime = nowTime
          // state.dateTime = [nowTime, nowTime]
          // 字典
          getDictByCodes(['OrderStage', 'PaymentType', 'DeliveryType']).then(res => state.dictMap = res.data).catch(e => console.log(e))
          // 获取供应商列表
          getSupplierSelector().then(res => state.supplierList = res.data).catch(e => console.log(e))
          // 获取部门列表
          getAllowDeptList().then(res => state.deptList = res.data).catch(e => console.log(e))
          // 用户报价单列表
          quoteSelector().then(res => state.quoteList = res.data).catch(e => console.log(e))
          // 商品名称列表
          purchaseOrderApi.getHistoryProducts().then(res => state.productNames = res.data).catch(e => console.log(e))
        }
        return flag
      },
      set: val => context.emit('update:code', val ? state.formData.type : '')
    })
    const state = reactive({
      formData: {
        type: 'PURCHASE_ORDER'  // 事项类型编码
      },
      formRules: {
        title: {required: true, message: '请填写采购主题', trigger: 'blur'},
        supplierInfoId: {required: true, message: '请选择供应商', trigger: 'change'},
        contactUserId: {required: true, message: '请选择卖方经办人', trigger: 'change'},
        amount: {required: true, message: '请填写合同金额', trigger: 'blur'}
      },
      dictMap: {},
      productNames: [],   // 产品名称列表
      supplierList: [],   // 用户供应商列表
      contactList: [],  // 供应商联系人列表
      deptList: [],   // 用户所在(有权限)的部门列表
      quoteList: [],  // 报价单列表
      selectedQuotes: [],   // 选中的报价单列表
      quoteVisible: false  // 关联报价单对话框
    })

    const supplierChange = (supplierInfoId) => {
      // 清空联系人以及联系人手机号
      if (supplierInfoId) {
        state.formData.contactPhone = state.formData.contactUserId = null
        // 重新加载供应商的联系人
        supplierContact.getContactList(supplierInfoId).then(res => state.contactList = res.data).catch(e => console.log(e))
      }
    }
    const closeMatter = () => {
      // 重置
      resetForm()
      context.emit('update:code', '')
      context.emit('callback')
    }
    // 新增产品
    const addProduct = () => {
      state.formData.productItems.push({
        id: null,
        name: null,
        ver: null,
        specification: null,
        num: 0,
        price: 0.00,
        total: 0.00,
        // deliveryType: '0', 2023-06-13移去订单
        remark: null
      })
    }
    const contactChange = (contactId) => {
      for (let i = 0; i < state.contactList.length; i++) {
        let contact = state.contactList[i]
        if (contact.id === contactId) {
          state.formData.contactPhone = contact.phone
          break
        }
      }
    }
    // 产品合计
    const calAmount = (product) => {
      let total = 0
      product.total = ((product.num || 0) * (product.price || 0)).toFixed(2)
      state.formData.productItems.forEach(item => total += (item.num || 0) * (item.price || 0))
      state.formData.realAmount = total.toFixed(2)
    }
    // 移除产品行
    const removeProduct = (index, product) => {
      state.formData.productItems.splice(index, 1)
      state.formData.realAmount -= product.total
    }
    // 打开关联报价单对话框
    const openQuoteAdd = () => {
      state.selectedQuotes = []
      if (state.formData.quotationList) {
        state.formData.quotationList.forEach(item => state.selectedQuotes.push(item.id))
      }
      state.quoteVisible = true
    }
    // 保存选择的报价单
    const confirmQuote = () => {
      state.formData.quotationList = []
      state.selectedQuotes.forEach(quoteId => {
        for (let i = 0; i < state.quoteList.length; i++) {
          let item = state.quoteList[i]
          if (item.id == quoteId) {
            state.formData.quotationList.push(item)
            break
          }
        }
      })
      state.selectedQuotes = []
      state.quoteVisible = false
    }
    // 移除报价单
    const removeQuotation = (index) => {
      state.formData.quotationList.splice(index, 1)
    }
    // 是否开票改变
    const invoiceChange = (val) => {
      state.formData.invoiceType = val == 1 ? 0 : null
    }
    // 保存草稿
    const saveDraft = (formRef) => {
      formRef.validate(valid => {
        if (!valid) {
          return false
        }
        purchaseOrderApi.saveDraft(state.formData).then(res => {
          if (res.data && res.data.id) {
            ElMessage.success('成功保存草稿！')
            closeMatter()
          }
        }).catch(e => console.log(e))
      })
    }
    // 保存到列表 & 保存并提交
    const saveOrder = (formRef, toMatter) => {
      state.formData.toMatter = toMatter
      formRef.validate(valid => {
        if (!valid) {
          return false
        }
        purchaseOrderApi.createOrder(state.formData).then(res => {
          if (res.data && res.data.id) {
            ElMessage.success(toMatter == 0 ? '保存成功！' : '提交成功！')
            closeMatter()
          }
        })
      })
    }
    const resetForm = () => {
      // 重置
      state.formData = {
        title: '采购单',
        supplierInfoId: null,
        actionStartTime: null,
        actionEndTime: null,
        executorIds: [],
        orderType: 1,   // 0个人 1企业
        content: '',
        contactUserId: null,
        contactPhone: null,
        deptId: null,   // 部门id
        stage: null,    // 阶段值
        offerNo: null,  // 采购单号
        occurDate: null,  // 预计交货日期
        amount: null,   // 合同金额
        realAmount: null, // 总金额
        payType: null,  // 结款方式 字典PaymentType
        includeTax: 0,    // 是否含税 0不含税 1含税
        invoice: 0,   // 是否开票 0否 1是
        invoiceType: null,   // 发票类型 0普通 1增值
        productItems: [],   // 产品清单列表
        quotationList: [],  // 报价单列表
        replenishInstruction: null,   // 合同正文&条款
        directSend: null,   // 是否可以直发, 0否 1是
        sourceType: '2',    // 订单来源, 字典orderSourceType, 2手工录入
        deliveryType: '0',  // 发货方式
        remark: null,
        attach: '',
        attachNames: '',
        priority: 0,
        remindState: 'NONE',
        remindType: '',
        type: 'PURCHASE_ORDER'  // 事项类型编码
      }
    }

    return {
      ...toRefs(state),
      formRef,
      resetForm,
      closeMatter,
      drawer,
      supplierChange,
      Plus,
      Delete,
      calAmount,
      addProduct,
      removeQuotation,
      openQuoteAdd,
      confirmQuote,
      saveDraft,
      saveOrder,
      contactChange,
      invoiceChange,
      removeProduct,
      numToChinese
    }
  }
}
</script>

<style scoped lang="scss">
:deep(.el-row) {
  margin-bottom: 18px;
}

:deep(.el-divider) {
  margin: 30px 0;
}

:deep(.el-transfer-panel) {
  width: 330px;

  .el-input {
    width: 90%;
    height: auto;
  }
}
</style>
